<?php

namespace app\common\api\controller;

use app\common\controller\Log;
use app\common\model\Levels;
use app\common\model\Member;
use app\common\model\MemberFinance;
use app\common\model\MemberPackages;
use app\common\model\Packages;
use think\Controller;

final class Bonus extends Controller
{
    protected static $bonusRule = [];

    public function __construct()
    {
        self::$bonusRule = Db('BonusRule')->find();
    }

    /**
     * 会员激活
     * @param $uid
     * @param $active_id
     * @return bool|int
     */
    public function activation($uid, $active_id)
    {

        if ($active_id == PROJECTNUMBER) {
            $res = self::active($uid);
        } else {
            $res = self::active($uid, $active_id);
        }

        return $res;
    }

    /**
     * 会员报单额
     * @param array $user
     * @return array|false|mixed|\PDOStatement|string|\think\Model
     */
    public function billMoney($user = [])
    {
        if (config("IS_MORE_LEVEL")) {
            $bill_money = get_user_level_money($user['userrank'], get_bonus_rule(), 'level_money');
        } else {
            $bill_money = get_bonus_rule('money');
        }

        return $bill_money;
    }

    /**
     * 会员激活
     * @param $uid
     * @param $active_id
     * @return bool|int
     */
    private function active($uid, $active_id = 0)
    {
        $info = Db('member')->field('tuijianid')->find($uid);
        /* 激活用户需要更新字段，激活字段=1;*/
        $data['status'] = 1;
        $data['active_time'] = time();
        //激活用户
        $res1 = Db('member')->where('uid', $uid)->update($data);
        $res2 = Db('ucenter_member')->where('id', $uid)->setField('status', 1);

        if ($res1 && $res2) {
            Db('member')->where('uid', $info['tuijianid'])->setInc('recom_num', 1);
            return true;
        } else {
            return -103;//状态更改失败
        }
    }

    /**
     * 推荐奖，增加推荐人成长值
     * @param $uid
     * @param $total
     * @return bool
     */
    public function bonusRecom($uid, $total)
    {
        $user = Db('member')->where('uid', $uid)->find();
        $tinfo = Db('member')->field('uid,tdeep,userrank')->where('uid', $user['tuijianid'])->where('status', 'egt', 1)->find();
        if (!$tinfo) {
            return false;
        }

        $costTotaL = MemberPackages::getMaxCost($tinfo['uid']);
//        file_put_contents('sh.txt', $costTotaL, FILE_APPEND);
//        file_put_contents('sh.txt', $total, FILE_APPEND);

        $total = min($total, $costTotaL);
//        Log::insertLog($costTotaL);
        $recomRate = self::$bonusRule['recom_rate'];
        $recomMoney = $total * $recomRate;

        if ($recomMoney > 0) {
            self::bonusShare($recomMoney, 1, $tinfo['uid'], $user);
            //更新贡献值每日释放数量
            self::changeContributionRelease($tinfo['uid']);
        }
    }

    /**
     * Notes:增加成长值
     * User: Administrator
     * Date: 2023/9/8
     * Time: 8:43
     * @param $uid
     * @param $total
     * @param false $isUid 是否包含自己
     * @return false
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function addAchievement($uid, $total, $isUid = false)
    {
        $user = Db('member')->where('uid', $uid)->find();
        if (!$user['tuijianid']) {
            return false;
        }

        $growth_rate = self::$bonusRule['growth_rate'];
        $total *= $growth_rate;
        // 联盟成长值（直推）
        Db('member')->where('uid', $user['tuijianid'])->setInc('achievement1', $total);

        // 团队累计成长值
        if ($isUid == true) {
            $tuijianids = trim($user['tuijianids'] . $uid, ',');
        } else {
            $tuijianids = trim($user['tuijianids'], ',');
        }

        $map = [
            'uid' => ['in', $tuijianids],
            'status' => ['>=', 1],
        ];
        Db('member')->where($map)->setInc('achievement', $total);

        // 团队总成长值
        $map['recom_num'] = ['>', 2];
        $tusers = Member::field('uid,achievement,achievement2')->where($map)->order('tdeep desc')->select();
        if (!$tusers) {
            return false;
        }
        foreach ($tusers as $val) {
            $where = [
                'tuijianid' => $val->uid,
                'status' => ['>=', 1],
            ];

            $achievements = Member::where($where)->column('achievement');
            rsort($achievements);
            array_shift($achievements);
            array_shift($achievements);
            $achievement2 = array_sum($achievements);
            if ($achievement2 != $val['achievement2']) {
                Member::where('uid', $val['uid'])->update(['achievement2' => $achievement2]);
            }
        }
    }

    /**
     * 减少成长值
     * @param $uid
     * @param $total
     * @param bool $isUid
     * @return bool
     */
    public function reduceAchievement($uid, $total, $isUid = false)
    {
        $user = Db('member')->where('uid', $uid)->find();
        if (!$user['tuijianid']) {
            return false;
        }

        $growth_rate = self::$bonusRule['growth_rate'];
        $total *= $growth_rate;

        $memberFinanceModel = MemberFinance::where('uid', $uid)->find();
        $memberFinanceModel->hasgrowth -= $total;
        $memberFinanceModel->save();

        $type = array('recordtype' => 0, 'changetype' => 41, 'moneytype' => 7);
        $money = array('money' => $total, 'hasmoney' => $memberFinanceModel->hasgrowth);
        money_change($type, $uid, 0, $money);
        unset($type, $money);

        // 联盟成长值（直推）
        Db('member')->where('uid', $user['tuijianid'])->setDec('achievement1', $total);

        // 团队累计成长值
        if ($isUid == true) {
            $tuijianids = trim($user['tuijianids'] . $uid, ',');
        } else {
            $tuijianids = trim($user['tuijianids'], ',');
        }

        $map = [
            'uid' => ['in', $tuijianids],
            'status' => ['>=', 1],
        ];
        Db('member')->where($map)->setDec('achievement', $total);

        // 团队总成长值
        $map['recom_num'] = ['>', 2];
        $tusers = Member::field('uid,achievement,achievement2')->where($map)->order('tdeep desc')->select();
        if (!$tusers) {
            return false;
        }
        foreach ($tusers as $val) {
            $where = [
                'tuijianid' => $val->uid,
                'status' => ['>=', 1],
            ];

            $achievements = Member::where($where)->column('achievement');
            rsort($achievements);
            array_shift($achievements);
            array_shift($achievements);
            $achievement2 = array_sum($achievements);
            if ($achievement2 != $val['achievement2']) {
                Member::where('uid', $val['uid'])->update(['achievement2' => $achievement2]);
            }
        }
    }

    /**
     * 会员级别更新
     * @param $uid
     * @return bool
     */
    public function updateRank($uid)
    {
        $user = Db('member')->where('uid', $uid)->find();
        $tuijianids = trim($user['tuijianids'] . $uid, ',');
        $tinfos = Db('member')->field('uid')->where('uid', 'in', $tuijianids)->where('status', 'egt', 1)->order('tdeep desc')->select();
        if (!$tinfos) {
            return false;
        }

        foreach ($tinfos as $v1) {
            $this->updateRank1($v1->uid);
        }
    }

    /**
     * 会员更新级别（
     * 升级---1、签到时候，推荐人增加；2、购买包，包级别增加；3、下级购买包，联盟成长值增加；4、下级购买包，总成长值增加
     * 降级---1、消费包释放完毕，包级别降低；2、总成长值减少）
     * @param $uid
     */
    public function updateRank1($uid)
    {
        $user = Db('member')->field('uid,userrank,update_rank,recom_num,package_id,achievement1,achievement2')->where('uid', $uid)->find();
//        Log::insertLog($user);
        $levels = Levels::order('id asc')->select();
        $level = 0;

        foreach ($levels as $v2) {
            if ($user['recom_num'] >= $v2['num'] && $user['package_id'] >= $v2['package_id'] && $user['achievement1'] >= $v2['growth'] && $user['achievement2'] >= $v2['total_growth']) {
                $level = $v2['id'];
            }
        }

        if ($user['userrank'] > $level) {
            // 降级直接降
            Member::where('uid', $uid)->update(['userrank' => $level]);
            //更新贡献值每日释放数量
            self::changeContributionRelease($uid);
        } elseif ($user['userrank'] < $level) {
            // 升级需要申请
            if ($user['update_rank'] != $level) {
                Member::where('uid', $uid)->update(['update_rank' => $level]);
            }
        }
    }

    /**
     * 更新每日释放的贡献值（根据冻结的总额度和用户级别决定）
     * @param $uid
     */
    public static function changeContributionRelease($uid)
    {
        $total = MemberFinance::where('uid', $uid)->value('hascontribution');
        if (!$total) {
            return;
        }
        $userrank = Member::where('uid', $uid)->value('userrank');
        $releaseRate = Levels::where('id', $userrank)->value('contribution_release_rate');

        $money = $total * $releaseRate;
//        Log::insertLog('uid:' . $uid . '|' . $userrank . '|' . $releaseRate . '|' . $money);
        if ($money) {
            MemberFinance::where('uid', $uid)->update(['per_contribution' => $money]);
        }
    }

    /**
     * 更新每日消费卷释放额度
     * @param $uid
     */
    public function changeCpRelease($uid)
    {
        $memberFinanceModel = MemberFinance::where('uid', $uid)->find();
        if ($memberFinanceModel->hascp <= 0) {
            return;
        }

        $releaseRate = self::$bonusRule['cp_release_rate'];
        $memberFinanceModel->per_cp = $memberFinanceModel->hascp * $releaseRate;
        $memberFinanceModel->save();
    }

    /**
     * 贡献值释放
     * @param $uid
     */
    public function contribution_release($uid)
    {
        $memberFinanceModel = MemberFinance::where('uid', $uid)->find();
        if ($memberFinanceModel->per_contribution <= 0 || $memberFinanceModel->hascontribution <= 0) {
            return;
        }

//        $rate = round(self::$bonusRule['total_wealth'] / self::$bonusRule['total_tdb'], 2);
//        $activeMoney = round($memberFinanceModel->per_contribution / $rate, 2);
//        if (!$activeMoney) {
//            return;
//        }

        $activeMoney = $memberFinanceModel->per_contribution;

        $memberFinanceModel->hasactive += $activeMoney;
        $memberFinanceModel->allactive += $activeMoney;
        $memberFinanceModel->hascontribution -= $memberFinanceModel->per_contribution;
        $res = $memberFinanceModel->save();
        if (!$res) {
            return;
        }

        $changetype = 32;
        $type = array('recordtype' => 1, 'changetype' => $changetype, 'moneytype' => 1);
        $money = array('money' => $activeMoney, 'hasmoney' => $memberFinanceModel->hasactive);
        money_change($type, $uid, $uid, $money);
        unset($type, $money);

        $type = array('recordtype' => 0, 'changetype' => $changetype, 'moneytype' => 5);
        $money = array('money' => $memberFinanceModel->per_contribution, 'hasmoney' => $memberFinanceModel->hascontribution);
        money_change($type, $uid, 0, $money);
        unset($type, $money);
    }

    /**
     * 消费卷释放
     * @param $uid
     */
    public function cp_release($uid)
    {
        $memberFinanceModel = MemberFinance::where('uid', $uid)->find();
        if ($memberFinanceModel->per_cp <= 0 || $memberFinanceModel->hascp <= 0) {
            return;
        }

        $rate = round(self::$bonusRule['total_wealth'] / self::$bonusRule['total_tdb'], 2);
        $activeMoney = round($memberFinanceModel->per_cp / $rate, 2);
        if (!$activeMoney) {
            return;
        }

        $memberFinanceModel->hasactive += $activeMoney;
        $memberFinanceModel->allactive += $activeMoney;
        $memberFinanceModel->hascp -= $memberFinanceModel->per_cp;
        $res = $memberFinanceModel->save();
        if (!$res) {
            return;
        }

        $changetype = 38;
        $type = array('recordtype' => 1, 'changetype' => $changetype, 'moneytype' => 1);
        $money = array('money' => $activeMoney, 'hasmoney' => $memberFinanceModel->hasactive);
        money_change($type, $uid, $uid, $money);
        unset($type, $money);

        $type = array('recordtype' => 0, 'changetype' => $changetype, 'moneytype' => 4);
        $money = array('money' => $memberFinanceModel->per_cp, 'hasmoney' => $memberFinanceModel->hascp);
        money_change($type, $uid, 0, $money);
        unset($type, $money);
    }

    /**
     * 消费包释放
     * @param $uid
     */
    public function package_release($uid)
    {
        $memberPackages = MemberPackages::where('uid', $uid)->where('status', 1)->select();
        if (!$memberPackages) {
            return;
        }

        $packageId = Member::where('uid', $uid)->value('package_id');
        foreach ($memberPackages as $val) {
            $activeMoney = $val->per_output;
            $memberFinanceModel = MemberFinance::where('uid', $uid)->find();
            $memberFinanceModel->hasactive += $activeMoney;
            $memberFinanceModel->allactive += $activeMoney;
            $memberFinanceModel->save();

            $status = 1;
            if ($val->used_days + 1 >= $val->total_days) {
                $status = 0;
            }

            $data = [
                'used_days' => $val->used_days + 1,
                'status' => $status,
                'update_time' => time()
            ];

            Db('member_packages')->where('id', $val->id)->update($data);

            if ($data['status'] == 0) {
                // 减少自己和团队成长值
                $cost = Packages::where('id', $val->package_id)->value('cost');

                if ($val->rank == 1) {
                    $this->reduceAchievement($uid, $cost);
                } else {
                    $this->reduceAchievement($uid, $cost, true);
                }

                $this->updateRank($uid);// 团队降级

                if ($packageId == $val->package_id) {
                    $max_id = MemberPackages::where('uid', $uid)->where('status', 1)->max('package_id');
                    $max_id = $max_id > 0 ? $max_id : 0;
                    Member::where('uid', $uid)->setField('package_id', $max_id);

                    // 包级别降低，可能引起降级
                    $this->updateRank1($uid);
                }
            }

            $changetype = 25;
            $type = array('recordtype' => 1, 'changetype' => $changetype, 'moneytype' => 1);
            $money = array('money' => $activeMoney, 'hasmoney' => $memberFinanceModel->hasactive);
            money_change($type, $uid, 0, $money);
            unset($type, $money);
        }
    }

    /**
     * 奖金生成
     * @param $bonusmoney
     * @param $changetype
     * @param $uid
     * @param $fromuser
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function bonusShare($bonusmoney, $changetype, $uid, $fromuser)
    {
        $map['uid'] = $uid;
        $user = Db('member_finance')->where($map)->find();

        $tax_rate = self::$bonusRule['tax_rate'];
        if ($tax_rate > 100 || $tax_rate <= 0) {
            $tax = 0;
        } else {
            $tax = $tax_rate * 0.01;
        }

        $tax_money = $bonusmoney * $tax;
        $actulMoney = $bonusmoney - $tax_money;

        $data['hascontribution'] = $user['hascontribution'] + $actulMoney;
        $data['allcontribution'] = $user['allcontribution'] + $actulMoney;

        $res = Db('member_finance')->where($map)->update($data);

        if ($res) {
            self::bonus('BonusCount', $changetype, $user, $bonusmoney, $actulMoney);
            self::bonus('BonusTotal', $changetype, $user, $bonusmoney, $actulMoney);

            $user = Db('member_finance')->where($map)->find();

            $type = array('recordtype' => 1, 'changetype' => $changetype, 'moneytype' => 5);
            $money = array('money' => $actulMoney, 'hasmoney' => $user['hascontribution']);
            money_change($type, $uid, $fromuser['uid'], $money);
            unset($type, $money);

            finance2($changetype, $bonusmoney); //公司财务统计
        }
    }

    /**
     * @param $table
     * @param $bonustype
     * @param $touser
     * @param $money
     * @param $hasmoney
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    private function bonus($table, $bonustype, $touser, $money, $hasmoney)
    {
        if ($table == 'BonusCount' || $table == 'bonus_count') {
            $count_date = strtotime('today');
            $map['count_date'] = $count_date;
        } else {
            $count_date = time();
        }
        $BCount = Db($table);

        $map['userid'] = $touser['uid'];

        $bonusData = $BCount->where($map)->find();
        $field = 'bonus' . $bonustype;
        if ($bonusData) {
            $data[$field] = $bonusData[$field] + $money;
            $data['total'] = $bonusData['total'] + $hasmoney;
            $BCount->where($map)->update($data);
        } else {
            $data = array(
                'userid' => $touser['uid'],
                'usernumber' => $touser['usernumber'],
                'count_date' => $count_date
            );
            $data[$field] = $money;
            $data['total'] = $hasmoney;
            $BCount->insert($data);
        }
    }
}